package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"tieba_deseign/models"
)

var Db *gorm.DB

func LinkDb() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/db_post?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	Db.AutoMigrate(models.Post{})
	Db.AutoMigrate(models.Admin{})

}

// 为用户自身创建post
func CreatePost(db *gorm.DB, post *models.Post, admin *models.Admin) (*models.Post, error) {
	// 尝试创建记录
	newPost := models.Post{
		Title:   post.Title,
		Body:    post.Body,
		AdminId: admin.ID,
	}
	if err := db.Create(&newPost).Error; err != nil {
		return nil, err
	}
	// 返回创建成功的 Post 对象
	return &newPost, nil
}

// 获取用户所有post
func GetAllPosts(db *gorm.DB, admin models.Admin) ([]models.Post, error) {
	var posts []models.Post
	result := db.Where("admin_id = ?", admin.ID).Find(&posts)
	if result.Error != nil {
		return nil, result.Error
	}
	if result.RowsAffected == 0 {
		return []models.Post{}, nil
	}

	return posts, nil
}

// 用户根据id查询数据
func GetPostById(db *gorm.DB, postid int, admin models.Admin) (*models.Post, error) {
	var post models.Post
	//将查询到的结果存入post
	if err := db.Where("admin_id=?", admin.ID).Where("id=?", postid).First(&post).Error; err != nil {
		return nil, err
	}
	return &post, nil
}

// 根据id更新数据
func UpdatePost(db *gorm.DB, post *models.Post, postid int, admin models.Admin) (*models.Post, error) {
	var UpdatePost models.Post
	result := db.Model(&UpdatePost).Where("admin_id=?", admin.ID).Where("id = ?", postid).Updates(map[string]interface{}{
		"title": post.Title,
		"body":  post.Body,
	})
	if result.Error != nil {
		return nil, result.Error
	}
	return &UpdatePost, nil
}

// 根据id删除帖子
func DeletePost(db *gorm.DB, postid uint64, admin models.Admin) error {
	var DeletePost models.Post
	result := db.Where("admin_id=?", admin.ID).Where("id = ?", postid).Delete(&DeletePost)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// 根据用户密码获取用户数据
func GetAdminPassWord(db *gorm.DB, username string) (*models.Admin, error) {
	var Admin models.Admin
	result := db.Where("username=? ", username).First(&Admin)
	if result.Error != nil {
		return nil, result.Error
	}
	return &Admin, nil

}

// 创建用户数据
func CreateAdmin(db *gorm.DB, admin *models.Admin) (*models.Admin, error) {
	if err := db.Create(admin).Error; err != nil {
		return nil, err
	}
	return admin, nil
}

// 根据用户名查询用户数据
func FindUserByUserName(db *gorm.DB, admin_name string) (bool, error) {
	var Admin models.Admin
	result := db.Where("username = ?", admin_name).First(&Admin)
	if result.Error != nil {
		// 如果是记录未找到的错误，返回 false
		if result.Error == gorm.ErrRecordNotFound {
			return false, nil
		}
		// 其他错误（如数据库连接问题），可以打印日志或抛出异常
		fmt.Println("Database error:", result.Error)
		return false, result.Error
	}
	// 如果查询成功，返回 true
	return true, nil

}
